package cn.jw.starter.redis.core.event;

import java.nio.charset.StandardCharsets;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import com.alibaba.fastjson2.JSON;

import cn.jw.starter.redis.core.event.model.InnerRedisEventModel;
import cn.jw.starter.redis.core.event.model.JwSpringRedisEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 监听redis事件
 *
 * @author: wds_prc
 * @since: 2024/8/2 17:07
 */
@Slf4j
public class JwRedisEventListener implements MessageListener {

    private ApplicationContext context;

    public JwRedisEventListener(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] data = message.getBody();
        String body = new String(data, StandardCharsets.UTF_8);
        log.debug("收到redis发布的事件:{}", body);
        InnerRedisEventModel baseRedisEvent =
            JSON.parseObject(body, InnerRedisEventModel.class);
        JwSpringRedisEvent event =
            new JwSpringRedisEvent(this, baseRedisEvent.getEventId(),
                baseRedisEvent.getEventData());
        context.publishEvent(event);
    }
}
